package cn.shiva.redisunit.lock.redisson;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author shiva   2022-08-20 21:14
 */
@Slf4j
@Service
public class RedissonService {
    private static final String LOCK_DEDUCTION = "LOCK.DEDUCTION";
    @Autowired
    private RedissonClient redissonClient;

    //模拟扣费业务
    public void deduction() {
        // 普通的可重入锁
        RLock lock = redissonClient.getLock(LOCK_DEDUCTION);
        try {
            // lock.lock()会不断重试获取锁，一直循环
            // 尝试拿锁10s后停止重试,返回false
            // 具有Watch Dog 自动延期机制 默认续30s
            if (lock.tryLock(10, TimeUnit.SECONDS)) {
                log.info("执行业务代码......");
            }
            // 尝试拿锁100s后停止重试,返回false；没有Watch Dog ，10s后自动释放
            // lock.tryLock(100, 10, TimeUnit.SECONDS);
            // 公平锁 保证 Redisson 客户端线程将以其请求的顺序获得锁
            // RLock fairLock = redissonClient.getFairLock("fairLock");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //解锁
            lock.unlock();
        }
    }
}
